#include "mapwin.h"
#include <QVBoxLayout>
#include <QWebEngineSettings>
#include <QWebEnginePage>
#include <QAction>
#include <QWebEngineProfile>
#include <QTimer>
MapWin::MapWin(QWidget *parent) : QWidget(parent)
{

    setFixedSize(480, 854);  // 设置窗口大小为 480x854

    // 设置WebView
    webView = new QWebEngineView(this);

    // 允许跨域访问本地内容
    QWebEngineProfile::defaultProfile()->setHttpAcceptLanguage("en-US,en;q=0.9");

    //允许本地内容访问远程资源
    webView->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessRemoteUrls, true);
    webView->settings()->setAttribute(QWebEngineSettings::LocalContentCanAccessFileUrls, true);

    //初始化时先不加载页面
    //webView->load(QUrl("qrc:/res/map.html"));

    // 启用开发者工具调试
    QWebEnginePage *page = webView->page();
    page->setDevToolsPage(new QWebEnginePage(page));
    page->action(QWebEnginePage::InspectElement)->trigger();

    // 返回按钮
    backButton = new QPushButton("返回主界面", this);
    connect(backButton, &QPushButton::clicked, this, [this](){
        webView->page()->runJavaScript("clearTrack();"); // 返回时主动清除
        emit jumpToWidget();  //发送跳转信号
    });

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(webView);
    layout->addWidget(backButton);

    //启动gps并发送信号
    gps = new GpsParser(this);
    connect(gps, &GpsParser::newPosition, this, &MapWin::updatePosition);

}

void MapWin::showEvent(QShowEvent *event)
{
    QWidget::showEvent(event);

    // 每次显示时重新加载页面
    webView->load(QUrl("qrc:/res/map.html"));
    gps->startSimulation(); // 重启GPS模拟

    // 页面加载完成处理
    connect(webView, &QWebEngineView::loadFinished, [this](bool ok) {
        if (ok) {
            // 清除轨迹
            webView->page()->runJavaScript("clearTrack();");

            // 检查地图初始化状态
            QTimer *checkTimer = new QTimer(this);
            connect(checkTimer, &QTimer::timeout, [this, checkTimer]() {
                webView->page()->runJavaScript("window.mapLoaded", [this, checkTimer](const QVariant &result) {
                    if (result.toBool()) {
                        mapLoaded = true;
                        checkTimer->stop();
                        checkTimer->deleteLater();
                        qDebug() << "地图准备就绪";
                    }
                });
            });
            checkTimer->start(100);
        }
    });

    // 使用 QTimer::singleShot
    QTimer::singleShot(0, this, [this]() {
        connect(webView, &QWebEngineView::loadFinished, this, [this](bool ok) {
            if (ok) {
                // 清除轨迹
                webView->page()->runJavaScript("clearTrack();");

                // 检查地图初始化状态
                QTimer *checkTimer = new QTimer(this);
                connect(checkTimer, &QTimer::timeout, [this, checkTimer]() {
                    webView->page()->runJavaScript("window.mapLoaded", [this, checkTimer](const QVariant &result) {
                        if (result.toBool()) {
                            mapLoaded = true;
                            checkTimer->stop();
                            checkTimer->deleteLater();
                            qDebug() << "地图准备就绪";
                        }
                    });
                });
                checkTimer->start(100);
            }
        });
    });
}

void MapWin::updatePosition(double lng, double lat)
{
    // 确保地图已经初始化
    if (mapLoaded) {
        QString js = QString("drawNewPoint(%1, %2);").arg(lng).arg(lat);
        webView->page()->runJavaScript(js, [](const QVariant &result) {
            if (!result.isNull()) {
                qDebug() << "JS执行返回:" << result;
            }
        });
    } else {
        // 延迟调用，直到地图加载完成
        QTimer::singleShot(100, this, [this, lng, lat]() {
            updatePosition(lng, lat);
        });
    }
}
